package com.tingyuge.thinking.spring.ioc.overview.container;

import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * ioc容器示例
 *
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/15
 */
@Configuration
public class AnnotationApplicationContextAsIocContainerDemo {
    public static void main(String[] args) {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        //将当前类 AnnotationApplicationContextAsIocContainerDemo 作为配置类
        annotationConfigApplicationContext.register(AnnotationApplicationContextAsIocContainerDemo.class);
        annotationConfigApplicationContext.refresh();
        lookupCollectionByType(annotationConfigApplicationContext);
        annotationConfigApplicationContext.close();
    }

    @Bean
    public User user(){
        User user = new User();
        user.setName("小刀");
        return user;
    }
    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory =(ListableBeanFactory)beanFactory;
            Map<String, User> userMap = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有的User 集合对象:  "+userMap);
        }
    }
}
